package effective.ch03;

/**
 * @description: 覆盖equals时请遵守通用约定，对称性
 * @author: Fesine
 * @createTime:2017/1/8 21:32
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/1/8 21:32
 */
public class CaseInsensitiveString {
    private final String s;

    public CaseInsensitiveString(String s) {
        if (s == null)
            throw new NullPointerException();
        this.s = s;
    }

    //此方法无法解决对称性的原则
    //@Override
    //public boolean equals(Object o) {
    //    if(o instanceof CaseInsensitiveString)
    //        return s.equalsIgnoreCase(((CaseInsensitiveString) o).s);
    //    if (o instanceof String)
    //        return s.equalsIgnoreCase((String) o);
    //    return false;
    //}


    @Override
    public boolean equals(Object o) {
        return o instanceof CaseInsensitiveString && ((CaseInsensitiveString) o).s
                .equalsIgnoreCase(s);
    }

    public static void main(String[] args) {
        CaseInsensitiveString cis = new CaseInsensitiveString("Abcd");
        String s = "abcd";
        System.out.println(cis.equals(s));
        System.out.println(s.equals(cis));
    }

}
